package com.niiwoo.civet.mobile.controller.invest;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dto.request.QueryMoneyTotalRequestDTO;
import com.niiwoo.civet.account.dto.response.AccountBaseResponse;
import com.niiwoo.civet.account.dto.response.QueryMoneyTotalResponseDTO;
import com.niiwoo.civet.account.dto.response.RechargeOrderDTO;
import com.niiwoo.civet.account.service.AccountDubboService;
import com.niiwoo.civet.account.service.MoneyTotalDubboService;
import com.niiwoo.civet.account.service.recharge.RechargeDubboService;
import com.niiwoo.civet.mobile.vo.request.loan.DrainageEntranceRequsetVO;
import com.niiwoo.civet.mobile.vo.response.IsShowDrainageEntranceResponseVO;
import com.niiwoo.civet.mobile.vo.response.invest.AccountHomePageResponseVO;
import com.niiwoo.civet.mobile.vo.response.invest.InvestmentRateInfoResponseVO;
import com.niiwoo.civet.mobile.vo.response.invest.RecommendProjectInfoResponseVO;
import com.niiwoo.civet.mobile.vo.response.invest.RecommendProjectInfoResponseVO.ProjectInfo;
import com.niiwoo.civet.mobile.vo.response.user.UserNoviceStatusGuideResponseVO;
import com.niiwoo.civet.trade.constant.TradeRedisKey;
import com.niiwoo.civet.trade.dto.common.InvestEvaluationDTO;
import com.niiwoo.civet.trade.dto.response.RecommendInvestResponseDTO;
import com.niiwoo.civet.trade.dto.response.customsystem.QueryProjectInvestOrderResponseDTO;
import com.niiwoo.civet.trade.dto.response.invest.InvestmentRateInfoResponseDTO;
import com.niiwoo.civet.trade.enums.TradeConfigEnum;
import com.niiwoo.civet.trade.service.invest.InvestDubboService;
import com.niiwoo.civet.trade.service.invest.InvestOrderDetailDubboService;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.civet.user.dto.response.OrganizationInfoRespDTO;
import com.niiwoo.civet.user.service.OrganizationInfoDubboService;
import com.niiwoo.civet.user.service.UserBasicInfoDubboService;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.Empty;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/recommendInvestController")
@Api(tags = "推荐投资投资(李想)", description = "/recommendInvestController")
public class RecommendInvestController {

	private static final Logger logger = LoggerFactory.getLogger(RecommendInvestController.class);

	@Reference(version="1.0.0")
	private InvestDubboService  investDubboService;

	@Reference(version = "1.0.0")
	private ProjectDubboService projectDubboService;

	@Reference(version = "1.0.0")
	private MoneyTotalDubboService moneyTotalDubboService;

	@Reference(version = "1.0.0")
	private UserBasicInfoDubboService userBasicInfoDubboService;

	@Reference(version = "1.0.0")
	private AccountDubboService accountDubboService;

	@Reference(version = "1.0.0")
	private InvestOrderDetailDubboService investOrderDetailDubboService;

	@Reference(version = "1.0.0")
	private RechargeDubboService rechargeDubboService;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Reference(version = "1.0.0")
	private OrganizationInfoDubboService organizationInfoDubboService;


	@PostMapping("/getRecommendProjectInfo")
    @ApiOperation("获取首页推荐标的信息(刘春)")
    @AuthIgnore
    public Result<RecommendProjectInfoResponseVO> getRecommendProjectInfo() throws Exception {
		String userId = PrincipalContext.getUserId();
		RecommendInvestResponseDTO responseDTO = investDubboService.queryNoviceRecommendInvest(userId);
		RecommendProjectInfoResponseVO responseVO = new RecommendProjectInfoResponseVO();
    	responseVO.setProjectInfo(new ProjectInfo());
    	responseVO.setType(responseDTO.getType());
    	responseVO.setLabelInformation(responseDTO.getLabelInformation());
    	responseVO.setProjectAttribute(responseDTO.getProjectAttribute());
    	responseVO.setIsNovice(responseDTO.getIsNewProject() == (byte) 1 ? 1 : 2);
    	BeanUtils.copyProperties(responseDTO.getProjectInfo(), responseVO.getProjectInfo());
    	if(Objects.nonNull(responseDTO.getProjectInfo().getAddInerest())) {
    		RecommendProjectInfoResponseVO.ActivityInfoVo activityInfoVo = new RecommendProjectInfoResponseVO.ActivityInfoVo();
    		activityInfoVo.setActivityTitle(responseDTO.getProjectInfo().getActivityTitle());
    		activityInfoVo.setAddInerest(responseDTO.getProjectInfo().getAddInerest());
    		responseVO.setActivityInfoVo(activityInfoVo);
    	}
        return Result.with(responseVO);
    }

	@AuthIgnore
	@ApiOperation("是否展示借款入口(谢稳)")
	@PostMapping("/isShowDrainageEntrance")
	public Result<IsShowDrainageEntranceResponseVO> isShowDrainageEntrance(@RequestBody DrainageEntranceRequsetVO requsetVO) {

		IsShowDrainageEntranceResponseVO isShowDrainageEntranceResponseVO = new IsShowDrainageEntranceResponseVO();

		TradeConfigEnum tradeConfigEnum = TradeConfigEnum.HOME_PAGE_DISPLAY_LOAN_STATUS;
		String config = investDubboService.selectConfig(tradeConfigEnum);
		//0关闭，1 开启
		if("0".equals(config)){
			isShowDrainageEntranceResponseVO.setShowEntrance(false);
			return Result.with(isShowDrainageEntranceResponseVO);
		}
		String userId = PrincipalContext.getUserId();
		if(StringUtils.isBlank(userId)){
			isShowDrainageEntranceResponseVO.setShowEntrance(true);
			return Result.with(isShowDrainageEntranceResponseVO);
		}
		//5.6.0传入的选择的我要借款还是我要投资，先预留，以便于后续维护
		/*if(requsetVO.getIsInvest()){

		}*/
		//为了引流，所以放开借款入口，不管用户是否是借款人
		//boolean isShowFlag = projectDubboService.queryProjectCountByUserId(userId) > 0 ? true : false;
		boolean isShowFlag = true;
		isShowDrainageEntranceResponseVO.setShowEntrance(isShowFlag);
		return Result.with(isShowDrainageEntranceResponseVO);
	}


	@PostMapping("/getAccountHomePageInfoH5")
	@ApiOperation("H5账户首页信息-liaojunjun")
	public Result<AccountHomePageResponseVO> getAccountHomePageInfo() {
		String userId = PrincipalContext.getUserId();
		AccountBaseResponse accountBase = accountDubboService.getOrgAccount(userId, userId);
		QueryMoneyTotalRequestDTO queryMoneyTotalRequestDTO = new QueryMoneyTotalRequestDTO();
		queryMoneyTotalRequestDTO.setUserId(userId);
		if(accountBase != null) {
			queryMoneyTotalRequestDTO.setAccountId(accountBase.getAccountId());
		}
		logger.info("getAccountHomePageInfo userId:{}", queryMoneyTotalRequestDTO.getUserId());

		QueryMoneyTotalResponseDTO queryMoneyTotalResponseDTO = moneyTotalDubboService.queryMoneyTotal(queryMoneyTotalRequestDTO);
		AccountHomePageResponseVO responseVO = new AccountHomePageResponseVO();
		responseVO.setAccountAmount(queryMoneyTotalResponseDTO.getAmountTotal());
		responseVO.setAvailableAmount(queryMoneyTotalResponseDTO.getInvestorAvailableBalance().add(queryMoneyTotalResponseDTO.getBorrowerAvailableBalance()));
		responseVO.setDueInCorpusInterest(queryMoneyTotalResponseDTO.getDueInCorpusInterest());

		responseVO.setOnWayAmount(queryMoneyTotalResponseDTO.getOnWayAmount().subtract(queryMoneyTotalResponseDTO.getDueInCorpusInterest()));

		OrganizationInfoRespDTO userBasic = organizationInfoDubboService.selectById(userId);
		responseVO.setRegisterTime(userBasic.getCreateTime());
		responseVO.setUserNickName(userBasic.getNickName());
		responseVO.setHeadImage(userBasic.getHeadImage());
		logger.info("getAccountHomePageInfo userId:{}, response:{}", PrincipalContext.getUserId(), JSON.toJSON(responseVO));
		return Result.with(responseVO);
	}

	@PostMapping("/getNoviceStatusGuide")
	@ApiOperation("H5新手引导行为状态查询-谢稳")
	public Result<UserNoviceStatusGuideResponseVO> getNoviceStatusGuide() {
		String userId = PrincipalContext.getUserId();
		if (StringUtil.isBlank(userId)) {
			throw new BizException("USR10019");
		}
		UserNoviceStatusGuideResponseVO responseVO = new UserNoviceStatusGuideResponseVO();
		//查询是否开通投资账户
		AccountBaseResponse accountBaseResponse = accountDubboService.getNiiwooAccount(userId, UserRoleEnum.INVESTOR);
		//是否有过风险评测
		InvestEvaluationDTO investEvaluationDTO = investDubboService.getInvestEvaluationInfo(userId);
		//是否有过投资
		QueryProjectInvestOrderResponseDTO queryProjectInvestOrderResponseDTO = investOrderDetailDubboService.queryLastInvestOrderByUserId(userId);
		//是否有充值记录
		RechargeOrderDTO rechargeOrderDTO = rechargeDubboService.queryFirstRechrageSuccessRecord(userId);
		responseVO.setIsOpenAccount(accountBaseResponse != null ? (byte) 1 : (byte) 0);
		responseVO.setIsEvaluation(investEvaluationDTO.getHadEvaluate());
		responseVO.setIsInvest(queryProjectInvestOrderResponseDTO != null ? (byte) 1 : (byte) 0);
		responseVO.setIsRecharge(rechargeOrderDTO != null ? (byte) 1 : (byte) 0);

		String userIsFirstClickKey = TradeRedisKey.NOVICE_GUIDE_WINDOW;
		if (!redisTemplate.opsForSet().isMember(userIsFirstClickKey, userId)) {
			responseVO.setIsCheckProfit((byte) 0);
		} else {
			responseVO.setIsCheckProfit((byte) 1);
		}
		return Result.with(responseVO);
	}

	@PostMapping("/clickInvestOrderGuide")
	@ApiOperation("点击去查询时触发(xiewen)")
	public Result<Empty> clickInvestNewFlag() {
		String userId = PrincipalContext.getUserId();

		if (StringUtil.isBlank(userId)) {
			throw new BizException("USR10019");
		}

		QueryProjectInvestOrderResponseDTO queryProjectInvestOrderResponseDTO =
				investOrderDetailDubboService.queryLastInvestOrderByUserId(userId);

		if(queryProjectInvestOrderResponseDTO != null){

			String userIsShowPagekKey = TradeRedisKey.NOVICE_GUIDE_WINDOW;

			redisTemplate.opsForSet().add(userIsShowPagekKey, userId);
		}

		return Result.with(Empty.getInstance());
	}

	@ApiOperation("省心投资利率信息(谢稳)")
	@PostMapping("/investmentRateInfo/V560")
	@AuthIgnore
	public Result<InvestmentRateInfoResponseVO> investmentRateInfo() {
		String userId = PrincipalContext.getUserId();
		InvestmentRateInfoResponseVO responseVO = new InvestmentRateInfoResponseVO();
		InvestmentRateInfoResponseDTO dto = investDubboService.getInvestmentRateInfo(userId);
		List<InvestmentRateInfoResponseVO.DeadlineAndRateInfo> list = new ArrayList<>();
		if(dto.getIntelligenceInvest() != null){
			list.add(tranfer(dto.getIntelligenceInvest()));
		}
		list.add(tranfer(dto.getInvest()));
		if(dto.getDebtTransfer() != null){
			list.add(tranfer(dto.getDebtTransfer()));
		}
		responseVO.setProvincialInvestmentlist(list);
		return Result.with(responseVO);
	}

    private InvestmentRateInfoResponseVO.DeadlineAndRateInfo tranfer(InvestmentRateInfoResponseDTO.DeadlineAndRateInfo tranfer) {
        InvestmentRateInfoResponseVO.DeadlineAndRateInfo info = new InvestmentRateInfoResponseVO.DeadlineAndRateInfo();
        info.setDeadlineBegin(tranfer.getDeadlineBegin());
        info.setDeadlineEnd(tranfer.getDeadlineEnd());
        info.setDeadlineUnitBegin(tranfer.getDeadlineUnitBegin());
        info.setDeadlineUnitEnd(tranfer.getDeadlineUnitEnd());
        info.setRateBegin(tranfer.getRateBegin());
        info.setRateEnd(tranfer.getRateEnd());
        info.setType(tranfer.getType());
        info.setStartInvestAmount(tranfer.getStartInvestAmount());
        return info;
	}
}